const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const routes = express.Router();
const { qiniuUpload } = require('../controllers/Qiniucontrollers');

// 创建绝对路径的临时目录
const tempDir = path.resolve(__dirname, '../temp');
if (!fs.existsSync(tempDir)) {
  fs.mkdirSync(tempDir, { recursive: true });
}

const upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, tempDir)  // 使用验证过的绝对路径
    },
    filename: (req, file, cb) => {  // 添加文件名处理
      const ext = path.extname(file.originalname);
      cb(null, `${Date.now()}-${Math.random().toString(36).slice(2)}${ext}`);
    }
  }),
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['image', 'video', 'audio'];
    const isValid = allowedTypes.some(type => 
      file.mimetype.startsWith(type)
    );
    
    // 改进的错误处理
    if (isValid) {
      cb(null, true);
    } else {
      cb(new Error('仅允许上传图片、视频、音频文件'), false);
    }
  },
  limits: {  // 添加安全限制
    fileSize: 50 * 1024 * 1024, // 50MB
    files: 1
  }
});

// 添加错误处理中间件
const handleUploadError = (err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    return res.status(400).json({ 
      error: err.code === 'LIMIT_FILE_SIZE' 
        ? '文件大小超过50MB限制' 
        : err.message 
    });
  } else if (err) {
    return res.status(400).json({ error: err.message });
  }
  next();
};

routes.post('/upload',
  upload.single('file'),
  (req, res, next) => {
    console.log('[DEBUG] 收到文件:', req.file?.path);
    next();
  },
  handleUploadError,
  async (req, res) => {
    try {
      console.log('[DEBUG] 开始七牛云上传');
      await qiniuUpload(req, res);
    } catch (err) {
      console.error('[CRITICAL] 控制器崩溃:', err.stack);
      res.status(500).json({ error: '内部服务异常' });
    }
  }
);

module.exports = routes;